package top.foxhome.web.spiders.web;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import top.foxhome.web.spiders.Config;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 实现网站浏览功能
 */
public class WebEngine {
    private OkHttpClient mOkHttpClient;

    public WebEngine() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
    }

    public Document browse(String url) {
        Document document = null;
        try {
            Request request = new Request.Builder().url(url)
                    .addHeader("User-Agent", randomUserAgent())//随机使用浏览器标识
                    .build();
            Response response = mOkHttpClient.newCall(request).execute();
            document = Jsoup.parse(response.body().string());
        } catch (Exception e) {
        } finally {
            return document;
        }
    }


    /**
     * 随机出现浏览器标识
     *
     * @return
     */
    public String randomUserAgent() {
        Random random = new Random();
        int randomIndex = random.nextInt(Config.USER_AGENT_FLAG.length);
        return Config.USER_AGENT_FLAG[randomIndex];
    }
}
